package com.qf.utils.filter;

import com.qf.bean.Employee;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.ResourceBundle;

/**
 * IntelliJ IDEA -> person
 * 2019/11/25 15:52
 *
 * @author zmyao
 * 别看，我是渣渣。
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override//拦截器开始执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      //判断是否是匿名地址
        ResourceBundle anon = ResourceBundle.getBundle("anon");
        String requestURI = request.getRequestURI();
        if (anon.containsKey(requestURI)){
            return   true;
        }
        //判断session是否有值
        //根据结果跳转页面
        HttpSession session = request.getSession();
        Employee employee = (Employee)session.getAttribute("employee");
        if (employee !=  null ){
            return  true;
        }
        else {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print("<script>alert('请登录!');location.href='/login.jsp';</script>");
            return  false;
        }


    }

    @Override//l拦截器结束执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override//无论有没有异常都要执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
